package org.csu.jpetstore_manage_system.web;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.tomcat.util.bcel.Const;
import org.csu.jpetstore_manage_system.domain.Account;
import org.csu.jpetstore_manage_system.domain.JsonResult;
import org.csu.jpetstore_manage_system.persistence.DigestUtil;
import org.csu.jpetstore_manage_system.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;


@Controller
@SessionAttributes("loginAccount")
public class AccountController {

    @Autowired
    private AccountService accountService;

    private ModelAndView modelAndView = new ModelAndView();

    @GetMapping("/accounts")
    public ModelAndView accountTableForm(){
        List<Account> accountList = accountService.getAllAccount();
        modelAndView.addObject("accountList", accountList);
        modelAndView.setViewName("page/accounts");
        return modelAndView;
    }

    @GetMapping("/welcome")
    public String mainForm(){
        return "page/welcome";
    }

    @GetMapping("/index")
    public String indexPage(){
        return "/index";
    }

    @GetMapping("/loginForm")
    public String loginForm(){
        return "login";
    }

    @PostMapping("/login")
    public ModelAndView login(String username,
                        String password){
        //数据库SignOn表格的psw长度=32
        String MD5_password;
        try {
            MD5_password = DigestUtil.getMD5(password.getBytes());
            Account loginAccount = accountService.getAccount(username, MD5_password);
            if(loginAccount == null){
                modelAndView.addObject("loginMsg", "用户名或密码错误");
                modelAndView.setViewName("login");
                return modelAndView;
            }else{
                modelAndView.addObject("loginAccount", loginAccount);
                modelAndView.setViewName("index");
                return modelAndView;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return modelAndView;
    }

    @DeleteMapping("accounts/{id}")
    public Account deleteAccount(@PathVariable("id") String username){
        accountService.deleteAccountById(username);
        return accountService.getAccountByUsername("username");
    }

    //查看基本资料
    @GetMapping("accounts/edit")
    public String editAccount(){
        return "page/user-setting";
    }
    //保存基本资料
    @PostMapping("accounts/edit")
    @ResponseBody
    public String saveAccount(@RequestBody Account account){
        String username = account.getUsername();
        String phone = account.getPhone();
        String email = account.getEmail();
        System.out.println(username + "," + phone + "," + email);
        Account account1 = accountService.getAccountByUsername(username);
        account1.setPhone(phone);
        account1.setEmail(email);
        accountService.updateAccount(account1);
        return "保存成功";
    }

    //打开重置密码页面
    @GetMapping("accounts/resetPwd")
    public String resetPwd(){
        return "page/user-password";
    }


    @PostMapping("/resetPassword/{password}")
    @ResponseBody
    public String resetPassword(@RequestBody Account account,
                                @PathVariable("password") String password) {
        //数据库SignOn表格的psw长度=32
        String MD5_password_old;
        try {
            MD5_password_old = DigestUtil.getMD5(account.getPassword().getBytes());
            Account account1 = accountService.getAccount(account.getUsername(),MD5_password_old);
            if (account1 == null) {
                return "用户名或原密码错误！";
            }
            String MD5_password_new = DigestUtil.getMD5(password.getBytes());
            account1.setPassword(MD5_password_new);
            accountService.updateAccount(account1);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "修改成功！";
    }

    @PostMapping("/giteeLogin")
    @ResponseBody
    public String giteeLogin(){
        String redirect_uri="http://localhost:8080/index";
        String url="https://gitee.com/oauth/authorize?response_type=code"+
                "&client_id=27b50a9ae74a7c49e7cb3faa74783eda27cf726abccaf1cf932d5227fe37a1af"+
                "&redirect_uri="+ URLEncoder.encode(redirect_uri);
        return "redirect:"+url;
    }

//  发送短信验证码
    @PostMapping("/sendSms")
    @ResponseBody
    public Object sendSms(HttpServletRequest httpServletRequest, String phoneNumber) {
        try {
            //生成6位验证码
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            //设置超时时间(不必修改)
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            //(不必修改)
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化ascClient，("***"分别填写自己的AccessKey ID和Secret)
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tRcDv6uZsnAtYfJq5MB", "IQhb8WRDwM8OtvwFu8s9G6SGaMFAvt");
            //(不必修改)
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
            //(不必修改)
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象(不必修改)
            SendSmsRequest request = new SendSmsRequest();
            //****处填写接收方的手机号码
            request.setPhoneNumbers(phoneNumber);
            //****填写已申请的短信签名
            request.setSignName("阿里云短信测试");
            //****填写获得的短信模版CODE
            request.setTemplateCode("SMS_154950909");
            //笔者的短信模版中有${code}, 因此此处对应填写验证码
            request.setTemplateParam("{\"code\":\""+verifyCode+"\"}");
            //不必修改
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            //将生成的验证码和创建时间放到session中，后面验证从session中取
            HttpSession session = httpServletRequest.getSession();
            session.setAttribute("verifyCode",verifyCode);
            session.setAttribute("verifyCodeCreateTime",System.currentTimeMillis());
			return sendSmsResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

//  验证登陆
    @RequestMapping(value = "/doLogin",method = RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public Object doLogin(@RequestParam("verifyCode") String verifyCode ,HttpSession session){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setVerifyCode(verifyCode);
        try {
            if(session.getAttribute("verifyCodeCreateTime") !=null && (System.currentTimeMillis()-Long.valueOf(String.valueOf(session.getAttribute("verifyCodeCreateTime"))) )> 1000 * 60  ){
                session.removeAttribute("verifyCode");
                session.removeAttribute("verifyCodeCreateTime");
                jsonResult.setData("验证码过期");
            }
            else if (session.getAttribute("verifyCode") != null &&
                    jsonResult.getVerifyCode().equals(session.getAttribute("verifyCode"))){
                session.removeAttribute("verifyCode");
                session.removeAttribute("verifyCodeCreateTime");
                jsonResult.setData("登录成功");
            }else{
                jsonResult.setData("验证码错误");
            }

        }catch(Exception e){
            jsonResult.setData("登录失败");
            e.printStackTrace();
        }
        return jsonResult;
    }

    @GetMapping("/toPhoneLogin")
    public String toPhoneLogin(){
        return "page/phoneLoginPage";
    }

    @GetMapping("/toAccountLogin")
    public String toAccountLogin(){
        return "page/accountLoginPage";
    }
}
